﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web;
using System.Web.Caching;
using NHaml;
using IntraVision.Web.Toolkit;

namespace IntraVision.Web
{
    public class ViewFactory
    {
        /// <summary>
        /// Returns compiled view by specified controller, viewdata, template path and layout path
        /// </summary>
        /// <param name="controller">IController</param>
        /// <param name="viewData">ViewData</param>
        /// <param name="templatePath">Template path</param>
        /// <param name="layoutPath">Layout path</param>
        /// <returns></returns>
        public static Template GetView(IController controller, ViewData viewData, string templatePath, string layoutPath)
        {
            Utils.PerfCounter pc = new IntraVision.Web.Utils.PerfCounter();
            pc.Start();


            TemplateEngine te = new TemplateEngine();
            te.AddReference(controller.GetType().Assembly);
            te.AddReference(typeof(System.Linq.IQueryable<>).Assembly);
            List<string> templates = new List<string>();

            layoutPath = (!string.IsNullOrEmpty(layoutPath)) ? controller.Server.MapPath(layoutPath) : null;
            templatePath = (!string.IsNullOrEmpty(templatePath)) ? controller.Server.MapPath(templatePath) : null;

            var ct = te.Compile(templatePath, layoutPath, typeof(IntraVision.Web.Template));

            Template template = ct.CreateInstance() as Template;
            template.ViewData = viewData;

            return template;
        }
    }
}
